/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * BattleshipGameJFrame.java
 *
 * Created on 10/12/2011, 23:28:18
 */
package Excersize2_Swing;

import Excersize2_Swing.SwingConstants.BattleshipTypes;
import battleshipgame.logic.InvalidInputException;
//import battleshipgame.logic.Player.BattleshipTypes;
import java.awt.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import battleshipgame.logic.Board;
import battleshipgame.logic.Player.Direction;
import battleshipgame.logic.Player;
import java.util.ArrayList;
import battleshipgame.logic.Battleship;
import battleshipgame.manager.GameManager;
import battleshipgame.manager.XmlHandler;

/**
 *
 * @author אלירן
 */
public class BattleshipGameJFrame extends javax.swing.JFrame {

    private int counter;
    private ArrayList<Player> players;
    private Player focusedPlayer;
    int numOfPlayers;
    private ArrayList< SwingCommand> UndoList;
    private ArrayList< SwingCommand> RedoList;
    public CommandSetnUnSetBattleship currentCommand;

    /** Creates new form BattleshipGameJFrame */
    public BattleshipGameJFrame() {
        counter = 0;
        UndoList = new ArrayList<SwingCommand>();
        RedoList = new ArrayList<SwingCommand>();
        players = new ArrayList<Player>();
        initComponents();
        ManuallyinitComponents();
        currentCommand = new CommandSetnUnSetBattleship(SwingCommand.DO_OR_UNDO.DO,
                this);
    }

    private void ManuallyinitComponents() {
        HorV.add(Horizontal);
        HorV.add(Vertical);
        Horizontal.setSelected(true);
        Player player1 = new Player("Player1", 0);
        Player player2 = new Player("Player2", 1);
        player1.initBattleshipList(5);
        player2.initBattleshipList(5);
        players.add(player1);
        players.add(player2);
        boardPanel.add(new SubmarineBoardPanel(this, players.get(0)));
        focusedPlayer = players.get(0);
        boardPanel.add(new SubmarineBoardPanel(this, players.get(1)));
        PlayersList.add(new PlayerButton(players.get(0), this));
        PlayersList.add(new PlayerButton(players.get(1), this));
        counter += 2;
        this.repaint();
        PrintMessage("Welcome to battleship strategy GUI.");

    }

    public void AddCommand(CommandSetnUnSetBattleship command) {
    }

    public void AddPlayer(Player XMLplayer) {
        int size = players.size();
        if (size == 6) {
            PrintMessage("Too many players!");
            return;
        }
        counter++;
        String newname = "Player " + counter;
        while (isThereAPlayerWithThatName(newname)) {
            counter++;
            newname = "Player " + counter;
        }
        Player player;
        if (XMLplayer == null) {
            player = new Player(newname, size);
        } else {
            player = XMLplayer;
            player.setId(size);
        }
        players.add(player);
        changePlayerFocus(size);
        PlayersList.add(new PlayerButton(focusedPlayer, this));
        PlayersList.invalidate();
        PlayersList.validate();
        UndoList.add(new AddPlayerCommand(player, size, SwingCommand.DO_OR_UNDO.DO, this));
    }

    public void refreshPlayersList() {
        changePlayerFocus(0);
        PlayersList.removeAll();
        ArrayList<Player> temp = new ArrayList<Player>();
        int size = players.size();
        Player tempPlayer;
        for (int i = 0; i < size; i++) {
            tempPlayer = players.get(i);
            tempPlayer.setId(i);
            PlayersList.add(new PlayerButton(tempPlayer, this));
            temp.add(tempPlayer);
        }
        PlayersList.repaint();
        players = temp;
    }

    public void RemoveFocusedPlayer() {
        int size = players.size();
        if (size == 2) {
            PrintMessage("Too few players! Add another player first");
            return;
        }
        boolean flag = true;
        for (int i = 0; i < size && flag; i++) {
            if (players.get(i) == focusedPlayer) {
                players.remove(i);
                flag = false;
            }
        }
        refreshPlayersList();
        this.repaint();
        changePlayerFocus(0);
        UndoList.add(new AddPlayerCommand(focusedPlayer, size, SwingCommand.DO_OR_UNDO.UNDO, this));
    }

    public Direction GetDirectionFromRadioButton() {
        if (Horizontal.isSelected()) {
            return Direction.HORIZONTAL;
        } else {
            return Direction.VERTICAL;
        }
    }

    public Player getPlayer(int id) {
        return players.get(id);
    }

    public void changePlayerFocus(int id) {
        focusedPlayer = getPlayer(id);
        boardPanel.removeAll();
        boardPanel.add(new SubmarineBoardPanel(this, focusedPlayer));
        boardPanel.repaint();
        this.repaint();
        this.validate();
        boardPanel.validate();
        PrintMessage("Player named " + focusedPlayer.getName() + " was chosen");
        ArrayList<BattleshipTypes> battleshipTypeses = focusedPlayer.getBattleshipTypeses();
        AirCraftCarrier.setEnabled(true);
        battleship.setEnabled(true);
        cruiser.setEnabled(true);
        Destroyer.setEnabled(true);
        submarine.setEnabled(true);
        int size = battleshipTypeses.size();
        for (int i = 0; i < size; i++) {
            switch (battleshipTypeses.get(i)) {
                case AIRCRAFT_CARRIER:
                    AirCraftCarrier.setEnabled(false);
                    break;
                case BATTLESHIP:
                    battleship.setEnabled(false);
                    break;
                case CRUSIER:
                    cruiser.setEnabled(false);
                    break;
                case DESTROYER:
                    Destroyer.setEnabled(false);
                    break;
                case SUBMARINE:
                    submarine.setEnabled(false);
                    break;
            }
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        HorV = new javax.swing.ButtonGroup();
        PlayersOneCardPanel = new javax.swing.JPanel();
        jSplitPane1 = new javax.swing.JSplitPane();
        BattleshipSelection = new javax.swing.JPanel();
        AirCraftCarrier = new javax.swing.JButton();
        battleship = new javax.swing.JButton();
        submarine = new javax.swing.JButton();
        cruiser = new javax.swing.JButton();
        Destroyer = new javax.swing.JButton();
        nameText = new javax.swing.JTextField();
        Vertical = new javax.swing.JRadioButton();
        Horizontal = new javax.swing.JRadioButton();
        NameLabel = new javax.swing.JLabel();
        Undo = new javax.swing.JButton();
        addANewPlayer = new javax.swing.JButton();
        deletePlayer = new javax.swing.JButton();
        jRadioButton1 = new javax.swing.JRadioButton();
        jRadioButton2 = new javax.swing.JRadioButton();
        redo = new javax.swing.JButton();
        boardPanel = new javax.swing.JPanel();
        MessageBoard = new javax.swing.JLabel();
        PlayersList = new javax.swing.JPanel();
        readFromXML = new javax.swing.JButton();
        SaveToXML = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        AirCraftCarrier.setText("Air-Craft Carrier[5]");
        AirCraftCarrier.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                AirCraftCarrierMouseClicked(evt);
            }
        });

        battleship.setText("Battleship[4]");
        battleship.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                battleshipMouseClicked(evt);
            }
        });

        submarine.setText("Submarine[3]");
        submarine.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                submarineMouseClicked(evt);
            }
        });

        cruiser.setText("Cruiser[3]");
        cruiser.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                cruiserMouseClicked(evt);
            }
        });

        Destroyer.setText("Destroyer[2]");
        Destroyer.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                DestroyerMouseClicked(evt);
            }
        });

        nameText.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nameTextActionPerformed(evt);
            }
        });
        nameText.addInputMethodListener(new java.awt.event.InputMethodListener() {
            public void caretPositionChanged(java.awt.event.InputMethodEvent evt) {
            }
            public void inputMethodTextChanged(java.awt.event.InputMethodEvent evt) {
                nameTextInputMethodTextChanged(evt);
            }
        });

        Vertical.setText("Vertical");

        Horizontal.setText("Horizontal");
        Horizontal.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                HorizontalActionPerformed(evt);
            }
        });

        NameLabel.setText("Name");

        Undo.setText("Undo");
        Undo.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                UndoMouseClicked(evt);
            }
        });

        addANewPlayer.setText("Add a new player");
        addANewPlayer.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                addANewPlayerMouseClicked(evt);
            }
        });

        deletePlayer.setText("Delete this player");
        deletePlayer.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                deletePlayerMouseClicked(evt);
            }
        });

        jRadioButton1.setText("Human");

        jRadioButton2.setText("AI");

        redo.setText("Redo");
        redo.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                redoMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout BattleshipSelectionLayout = new javax.swing.GroupLayout(BattleshipSelection);
        BattleshipSelection.setLayout(BattleshipSelectionLayout);
        BattleshipSelectionLayout.setHorizontalGroup(
            BattleshipSelectionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(BattleshipSelectionLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(BattleshipSelectionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, BattleshipSelectionLayout.createSequentialGroup()
                        .addComponent(jRadioButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jRadioButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(13, 13, 13))
                    .addGroup(BattleshipSelectionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(deletePlayer, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(addANewPlayer, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(Horizontal, javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(NameLabel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(submarine, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(nameText, javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(AirCraftCarrier, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(battleship, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(cruiser, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(Destroyer, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(Vertical, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, BattleshipSelectionLayout.createSequentialGroup()
                            .addComponent(Undo, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(redo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addContainerGap())
        );
        BattleshipSelectionLayout.setVerticalGroup(
            BattleshipSelectionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(BattleshipSelectionLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(NameLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(nameText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(AirCraftCarrier)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(battleship)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(submarine)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cruiser)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(Destroyer)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(Horizontal)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(Vertical)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(BattleshipSelectionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(Undo)
                    .addComponent(redo))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(addANewPlayer)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(deletePlayer)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(BattleshipSelectionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jRadioButton1)
                    .addComponent(jRadioButton2))
                .addContainerGap(17, Short.MAX_VALUE))
        );

        jSplitPane1.setLeftComponent(BattleshipSelection);

        boardPanel.setLayout(new java.awt.BorderLayout());
        jSplitPane1.setRightComponent(boardPanel);

        javax.swing.GroupLayout PlayersOneCardPanelLayout = new javax.swing.GroupLayout(PlayersOneCardPanel);
        PlayersOneCardPanel.setLayout(PlayersOneCardPanelLayout);
        PlayersOneCardPanelLayout.setHorizontalGroup(
            PlayersOneCardPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, PlayersOneCardPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(PlayersOneCardPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jSplitPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 583, Short.MAX_VALUE)
                    .addComponent(MessageBoard, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 583, Short.MAX_VALUE))
                .addContainerGap())
        );
        PlayersOneCardPanelLayout.setVerticalGroup(
            PlayersOneCardPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(PlayersOneCardPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(MessageBoard, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 376, Short.MAX_VALUE)
                .addContainerGap())
        );

        PlayersList.setLayout(new java.awt.GridLayout(6, 1));

        readFromXML.setText("Read From XML");
        readFromXML.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                readFromXMLMouseClicked(evt);
            }
        });

        SaveToXML.setText("Save To XML");
        SaveToXML.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                SaveToXMLMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(PlayersOneCardPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(27, 27, 27)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(SaveToXML, javax.swing.GroupLayout.DEFAULT_SIZE, 107, Short.MAX_VALUE)
                    .addComponent(PlayersList, javax.swing.GroupLayout.DEFAULT_SIZE, 107, Short.MAX_VALUE)
                    .addComponent(readFromXML, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(50, 50, 50))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(PlayersOneCardPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(readFromXML, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(SaveToXML, javax.swing.GroupLayout.DEFAULT_SIZE, 42, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(PlayersList, javax.swing.GroupLayout.PREFERRED_SIZE, 323, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void HorizontalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_HorizontalActionPerformed
// TODO add your handling code here:
    Direction direction = Direction.HORIZONTAL;
}//GEN-LAST:event_HorizontalActionPerformed

private void AirCraftCarrierMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_AirCraftCarrierMouseClicked
    GeneralBattelshipButtonMouseClicked(evt, SwingConstants.BattleshipTypes.AIRCRAFT_CARRIER);
}//GEN-LAST:event_AirCraftCarrierMouseClicked

private void battleshipMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_battleshipMouseClicked
    GeneralBattelshipButtonMouseClicked(evt, SwingConstants.BattleshipTypes.BATTLESHIP);

}//GEN-LAST:event_battleshipMouseClicked

private void submarineMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_submarineMouseClicked
    GeneralBattelshipButtonMouseClicked(evt, SwingConstants.BattleshipTypes.SUBMARINE);

}//GEN-LAST:event_submarineMouseClicked

private void cruiserMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cruiserMouseClicked
    GeneralBattelshipButtonMouseClicked(evt, SwingConstants.BattleshipTypes.CRUSIER);
}//GEN-LAST:event_cruiserMouseClicked

private void DestroyerMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_DestroyerMouseClicked
// TODO add your handling code here:
    GeneralBattelshipButtonMouseClicked(evt, SwingConstants.BattleshipTypes.DESTROYER);
}//GEN-LAST:event_DestroyerMouseClicked

private void addANewPlayerMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_addANewPlayerMouseClicked
// TODO add your handling code here:
    AddPlayer(null);
}//GEN-LAST:event_addANewPlayerMouseClicked

private void deletePlayerMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_deletePlayerMouseClicked
// TODO add your handling code here:
    RemoveFocusedPlayer();
}//GEN-LAST:event_deletePlayerMouseClicked

private void nameTextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nameTextActionPerformed
// TODO add your handling code here:
    focusedPlayer.setNickname(nameText.getText());
    refreshPlayersList();

}//GEN-LAST:event_nameTextActionPerformed

private void nameTextInputMethodTextChanged(java.awt.event.InputMethodEvent evt) {//GEN-FIRST:event_nameTextInputMethodTextChanged
// TODO add your handling code here:
    String tempname = nameText.getText();
    if (!isThereAPlayerWithThatName(tempname)) {
        focusedPlayer.setNickname(tempname);
        players.get(focusedPlayer.getId());
    } else {
        PrintMessage("There is already a player with that name!");
    }
    nameText.setText("");
}//GEN-LAST:event_nameTextInputMethodTextChanged

private void readFromXMLMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_readFromXMLMouseClicked
// TODO add your handling code here:
    ArrayList<Player> tempPlayersList = getPlayersFromXml();
    int size = tempPlayersList.size();
    PlayersList.removeAll();
    players.removeAll(players);
    for (int i = 0; i < size; i++) {
        AddPlayer(tempPlayersList.get(i));
    }
}//GEN-LAST:event_readFromXMLMouseClicked

private void SaveToXMLMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_SaveToXMLMouseClicked
    int size = players.size();
    for (int i = 0; i < size; i++) {
        if (players.get(i).getTotalBattleship() != 5){
            PrintMessage("Too few battleships in one or more of the players");//check whatever is written in the message
            return;
        }
            
    }
    GameManager gameManager = new GameManager();
    gameManager.players = players;
    XmlHandler.saveGameDataToXml(gameManager);
}//GEN-LAST:event_SaveToXMLMouseClicked

private void UndoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_UndoMouseClicked
// TODO add your handling code here:
    int size = UndoList.size();
    UndoList.get(size-1).RevertCommand();
    RedoList.add(UndoList.get(size-1)) ;
}//GEN-LAST:event_UndoMouseClicked

private void redoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_redoMouseClicked
// TODO add your handling code here:
    int size = UndoList.size();
    if (size ==0 ) 
        return;
    RedoList.get(size-1).RevertCommand();
}//GEN-LAST:event_redoMouseClicked
    private void SetBattleshipToCurrentCommand(SwingConstants.BattleshipTypes bt) {
        currentCommand.setBattleshipSize(SwingConstants.getBattleshipSize(bt));//REPAIR
    }

    private void GeneralBattelshipButtonMouseClicked(java.awt.event.MouseEvent evt, SwingConstants.BattleshipTypes bt) {
        // all batlleship mouseclicks use this method
        int size = SwingConstants.getBattleshipSize(bt); 

        String message = "Battleship of size " + size + " in the board. make sure you choose direction also";
        MessageBoard.setText(message);
        currentCommand.setBattleshipSize(size);
        currentCommand.setBattleshipType(bt);
        currentCommand.setDirection(GetDirectionFromRadioButton());
        currentCommand.setEnabled(true);
    }

    public void PrintMessage(String string) {
        MessageBoard.setText(string);
    } 

    public void SetBattleshipInBoard(CommandSetnUnSetBattleship command) {
        int size = command.getBattleshipSize();
        String coordinate = command.getCoordinate();
        String direction;
        if (command.getDirection() == Direction.HORIZONTAL) {
            direction = "Horizontally";
        } else {
            direction = "Vertically";
        }
        String message = "battleship of size " + size + " in " + coordinate + " " + direction;
        MessageBoard.setText(message);
        AddCommand(command); 
        currentCommand = new CommandSetnUnSetBattleship(SwingCommand.DO_OR_UNDO.DO , this);
        Battleship tempBattleship = new battleshipgame.logic.Battleship(SwingConstants.getBattleshipString(command.getBattleshipTypes()), size);
        try {
            focusedPlayer.SetBattleshipInBoard(tempBattleship, coordinate, command.getDirection());
            changePlayerFocus(focusedPlayer.getId());
        } catch (InvalidInputException ex) {
            PrintMessage("Could not place this battleship here");
        }
        command.do_or_undo = SwingCommand.DO_OR_UNDO.DO ;
        command.setPlayer(focusedPlayer);
        boolean add = UndoList.add(command);
    }
    public void removeBattleshipFromBoard (Battleship battleship) {
        try {
            focusedPlayer.RemovBattleshipFromBoard(battleship);
            changePlayerFocus(focusedPlayer.getId());
        } catch (InvalidInputException ex) {
            PrintMessage("Something went wrong.");
        }
        CommandSetnUnSetBattleship command =new CommandSetnUnSetBattleship(SwingCommand.DO_OR_UNDO.UNDO, this);
        
        command.setBattleship(battleship);
        command.setPlayer(focusedPlayer);
        UndoList.add(command);
    }
    private boolean isThereAPlayerWithThatName(String name) {
        boolean res = false;
        int size = players.size();
        for (int i = 0; i < size; i++) {
            res = (name.equals(players.get(i).getName())) || res;
        }
        return res;
    }
    private void addPlayerToPlayers(Player player) {
        players.add(player);
    }
    private ArrayList<Player> getPlayersFromXml() {
        ArrayList<Player> res;
        GameManager gameManager = new GameManager();
        try {
            XmlHandler.getGameDataFromXml(gameManager);
        } catch (InvalidInputException ex) {
            Logger.getLogger(BattleshipGameJFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
        res = gameManager.getPlayers();
        return res;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(BattleshipGameJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(BattleshipGameJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(BattleshipGameJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(BattleshipGameJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new BattleshipGameJFrame().setVisible(true);

            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton AirCraftCarrier;
    private javax.swing.JPanel BattleshipSelection;
    private javax.swing.JButton Destroyer;
    private javax.swing.ButtonGroup HorV;
    private javax.swing.JRadioButton Horizontal;
    private javax.swing.JLabel MessageBoard;
    private javax.swing.JLabel NameLabel;
    private javax.swing.JPanel PlayersList;
    private javax.swing.JPanel PlayersOneCardPanel;
    private javax.swing.JButton SaveToXML;
    private javax.swing.JButton Undo;
    private javax.swing.JRadioButton Vertical;
    private javax.swing.JButton addANewPlayer;
    private javax.swing.JButton battleship;
    private javax.swing.JPanel boardPanel;
    private javax.swing.JButton cruiser;
    private javax.swing.JButton deletePlayer;
    private javax.swing.JRadioButton jRadioButton1;
    private javax.swing.JRadioButton jRadioButton2;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JTextField nameText;
    private javax.swing.JButton readFromXML;
    private javax.swing.JButton redo;
    private javax.swing.JButton submarine;
    // End of variables declaration//GEN-END:variables
}
